const { src, dest, parallel, series, watch } = require("gulp");
const del = require("del");
//自动加载插件
//cnpm i gulp-load-plugins --save-dev
const gulpLoadPlugins = require("gulp-load-plugins");
const plugins = gulpLoadPlugins();

//使用开发服务器
const browserSync = require("browser-sync");
const bs = browserSync.create();
const serve = () => {
  watch("src/assets/styles/*.scss", style);
  watch("src/assets/scripts/*.js", script);
  watch("src/assets/swig/*.html", page);
  // watch("src/assets/images/**", image);
  // watch("src/assets/fonts/**", font);
  // watch("public/**", extra);
  watch(
    ["src/assets/images/**", "src/assets/fonts/**", "public/**"],
    bs.reload
  );
  bs.init({
    notify: false,
    port: 2080,
    // open:false,
    files: "dist/**",
    server: {
      baseDir: ["dist", "src", "public"],
      routes: {
        "/node_modules": "node_modules",
      },
    },
  });
};

//删除dist
//cnpm i del --save-dev
const clean = () => {
  return del(["dist"]);
};

// scss样式编译
const style = () => {
  return src("src/assets/styles/*.scss", { base: "src" })
    .pipe(plugins.sass(require("sass"))({ outputStyle: "expanded" }))
    .pipe(dest("dist"));
};

//es6脚本编译,cnpm i @babel/core --save-dev ,cnpm i @babel/preset-env --save-dev
const script = () => {
  return src("src/assets/scripts/*.js", { base: "src" })
    .pipe(plugins.babel({ presets: ["@babel/preset-env"] }))
    .pipe(dest("dist"));
};

//页面swig模板编译
//cnpm install gulp-swig --save-dev
let data = {
  title: "我在北京天安门",
  date: new Date(),
};
const page = () => {
  return src("src/assets/swig/*.html", { base: "src" })
    .pipe(plugins.swig({ data }))
    .pipe(dest("dist"));
};

//图片与字体文件转换
//cnpm install gulp-imagemin --save-dev
const image = () => {
  return src("src/assets/images/**", { base: "src" })
    .pipe(plugins.imagemin())
    .pipe(dest("dist"));
};
const font = () => {
  return src("src/assets/fonts/**", { base: "src" })
    .pipe(plugins.imagemin())
    .pipe(dest("dist"));
};

//其他文件处理
const extra = () => {
  return src("public/**", { base: "public" }).pipe(dest("dist"));
};

const compile = parallel(style, script, page);
const build = series(clean, parallel(compile, image, font, extra));
const develop = series(compile, serve);

module.exports = {
  style,
  script,
  page,
  image,
  extra,
  clean,
  serve,
  compile,
  build,
  develop,
};
